package com.chenjiajin.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.chenjiajin.domain.DemoExport;
import com.chenjiajin.domain.DemoImport;
import com.chenjiajin.mapper.DemoImportMapper;
import com.chenjiajin.service.TestService;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private DemoImportMapper mapper;

    @Override
    public void saveBatch(List<DemoImport> list) {
        for (DemoImport item : list) {
            mapper.insert(item);
        }
    }

    @Override
    public void bb(HttpServletResponse response) throws IOException, URISyntaxException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", String.format("attachment; filename=%s", URLEncoder.encode("导出简单案例.xlsx", "UTF-8")));


        WriteCellStyle headStyle = new WriteCellStyle();  // 标题

        //内容策略
        WriteCellStyle contentStyle = new WriteCellStyle();
        contentStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);   //设置 水平居中
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);  //设置 垂直居中
        // 字体策略
        WriteFont contentFont = new WriteFont();
        // 字体大小
        contentFont.setFontHeightInPoints((short) 12);
        contentStyle.setWriteFont(contentFont);

        HorizontalCellStyleStrategy horizontalCellStyleStrategy = new HorizontalCellStyleStrategy(headStyle, contentStyle);

        List<DemoExport> list = mapper.export();
        for (DemoExport item : list) {
            if (StringUtils.hasText(item.getImg())) {
                URL url = new URL(item.getImg());
                item.setImgUrl(url);
                item.setInputStream(url.openStream());
            }
        }

        EasyExcel.write(response.getOutputStream(), DemoExport.class)
                .sheet("订货单第一页")
                //.registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())   // 自适应宽度，但是这个不是特别精确
                .registerWriteHandler(horizontalCellStyleStrategy)              // 自定义样式
                .doWrite(list);


        // 动态指定写出的列:
        //Set<String> set = new HashSet<>();
        //set.add("name");    // 设置 要导出列的属性名 必须要跟类型的属性名保持一致
        //set.add("age");     //set存在的值就是能输出的列
        //
        //EasyExcel.write(response.getOutputStream(), DemoExport.class)
        //        .includeColumnFiledNames(set)
        //        .registerWriteHandler(new LongestMatchColumnWidthStyleStrategy())   // 自适应宽度，但是这个不是特别精确
        //        .sheet()
        //        .doWrite(list);

    }


    @Value("${excel.template}")
    private String template;

    @Override
    public void template(HttpServletResponse response) throws IOException {
        // 设置响应流
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-disposition", String.format("attachment; filename=%s", URLEncoder.encode("模板导出练习.xlsx", "UTF-8")));

        // 模板
        // 方式一: URL转为输入流
        //String urlStr = "https://gz-yuanmeng.oss-cn-guangzhou.aliyuncs.com/Excel%E5%AF%BC%E5%87%BA%E6%A8%A1%E6%9D%BF.xlsx";
        //InputStream inputStream = new URL(urlStr).openStream();
        // 方式二: 本地模板
        ClassPathResource resource = new ClassPathResource(template);
        InputStream inputStream = resource.getInputStream();

        // 数据
        List<DemoExport> dataList = mapper.export();
        for (DemoExport item : dataList) {
            if (StringUtils.hasText(item.getImg())) {
                URL url = new URL(item.getImg());
                item.setImgUrl(url);
                //item.setInputStream(url.openStream());
                // 模板导出的方式 , 不能使用 InputStream属性 , 可以使用URL属性
                // com.alibaba.excel.exception.ExcelDataConvertException: Can not find 'Converter' support class HttpInputStream.
            }
        }

        // 填充模板
        ExcelWriter workbook = EasyExcel.write(response.getOutputStream(), DemoExport.class)
                .withTemplate(inputStream)
                .build();
        WriteSheet sheet = EasyExcel.writerSheet().build();
        workbook.fill(dataList, sheet);
        workbook.finish();
    }


}

